package com.fitbet.api.service.impl;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.utils.JsonUtils;
import com.fitbet.api.handler.PaymentHandler;
import com.fitbet.api.service.SalesOrderService;
import com.fitbet.entity.trading.PaymentRequest;
import com.fitbet.entity.trading.SalesOrder;
import com.fitbet.entity.user.User;

/**
 *
 * @author Ark
 *         
 */
@Service("salesOrderService")
public class SalesOrderServiceImpl extends DataServiceImpl<SalesOrder> implements SalesOrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(SalesOrderServiceImpl.class);
    
    @Autowired
    private PaymentHandler      paymentHandler;
    
    /*
     * (non-Javadoc)
     * 
     * @see
     * com.edoomath.site.service.SalesOrderService#prepay(com.edoomath.entity.
     * trade.SalesOrder, com.edoomath.entity.user.User, java.lang.String)
     */
    public Map<String, Object> prepay(SalesOrder salesOrder, User user, String remoteIp) {
        
        try {
            
            // 1. create payment request
            PaymentRequest paymentRequest = new PaymentRequest(salesOrder.getCode(), salesOrder.getType());
            genericDaoSupport.save(paymentRequest.initliaze());
            
            logger.trace("#prepay() - Get remote IP address [{}].", remoteIp);
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("order_no", paymentRequest.getOrderCode());
            parameters.put("request_no", paymentRequest.getCode());
            parameters.put("user_id", user.getOpenid());
            parameters.put("channel", "wechatpay");
            parameters.put("amount", salesOrder.getPrice());
            String subject = salesOrder.getContent().replace(salesOrder.getUser().getNickname(), "");
            logger.trace("#prepay() Get subjuct [{}]", subject);
            parameters.put("subject", subject);
            
            // 2. generate wechat pay context
            Map<String, Object> wechatPayContext = paymentHandler.generateWechatPayContext(parameters);
            logger.trace("#prepay() - Get wechatPayContext here [{}]", JsonUtils.toJson(wechatPayContext));
            
            return wechatPayContext;
            
        } catch (Exception e) {
            logger.error("#prepay - occurs error", e);
            throw BusinessException.newInstance("500", "报名参与失败");
        }
    }
}
